<?php
include_once(dirname(__FILE__).'/../lib/Db.class.php');
include_once(dirname(__FILE__).'/../lib/Log.class.php');
class PriceCache{
    private $db;
    private $log;
    private static $cache;
    private static $UPDATE_TIME;

    private function __construct(){
        $this->db = Db::getInstance();
        $this->log = Log::getInstance();
        self::$UPDATE_TIME = 24*60*60;
    }
    /**
     * 获取价格缓存的实例
     * @return PriceCache
     */
    public static function getInstance(){
        if(self::$cache == null)
        {
            self::$cache = new PriceCache();
             return self::$cache;
        }
        else
            return self::$cache;
    }
    /**
     * 获取价格
     * 返回数据的格式：
     * array['id'] // 物品id
     * array['sell'] // 市场最低卖价
     * array['buy'] // 市场最高买价
     * @param  int $id 物品的id
     * @return [array]  
     */
    public function get($id){
        if($this->has($id)) // 存在缓存
        {
            if($this->checkTime($id)) // 是否更新缓存
                return $this->updateCache($id);
            else
                return $this->getCache($id);
        }
        else
            return $this->set($id);
    }
    private function updateCache($id){
        date_default_timezone_set('Asia/Shanghai');
        $time = strtotime('now');
        $price = $this->getPrice($id);
        $sql = 'update pricecache set sell='.$price['sell'].
                ',buy='.$price['buy'].',lastupdate='.
                $time.' where id='.$id;
        $this->db->update($sql);
        return $this->getCache($id);
    }
    // 获取缓存
    private function getCache($id){
        $sql = 'select * from pricecache where id='.$id;
        $callback = function($query_result){
            $row = $query_result[0];
            $result = array("id"=>$row->id,"sell"=>$row->sell,"buy"=>$row->buy);
            return $result;
        };
        return $this->db->db_query($sql,$callback);
    }
    private function getPrice($id){
        // 获取价格
        $url = "http://www.ceve-market.org/api/marketstat?typeid=".
                $id.'&regionlimit=10000002&usesystem=30000142';
        $ch = curl_init($url);
        if($ch == FALSE)
            die($this->log->log('curl_init() faild'));
        curl_setopt_array($ch,array(CURLOPT_RETURNTRANSFER=>true));
        $price = curl_exec($ch);
        if($price == FALSE)
            die($this->log->log('curl_exec() faild'));
        curl_close($ch);
        $xml = new SimpleXMLElement($price);

        $sell = $xml->marketstat->type->sell->min;
        $buy =  $xml->marketstat->type->buy->max;

        $price = array('id'=>$id,'sell'=>$sell,'buy'=>$buy);
        return $price;
    }
    // 设置缓存
    private function set($id){
        date_default_timezone_set('Asia/Shanghai');
        $price = $this->getPrice($id);
        $time = strtotime('now');
        if($time == FALSE)
            die($this->log->log('strtotime() faild'));
        $sql = 'insert into pricecache values('.$price['id'].','.$price['sell'].','.
                $price['buy'].','.$time.')';
        $this->db->insert($sql);
        return $this->getCache($id);
    }
    // 检测是否已存在缓存
    private function has($id){
        $sql = "select * from pricecache where id=".$id;
        $callback = function($query_result){
            $db = Db::getInstance();
            if($db->getRows())
                return TRUE;
            else
                return FALSE;
        };
        return $this->db->db_query($sql,$callback);
    }
    // 检测是否需要更新缓存
    private function checkTime($id){
        date_default_timezone_set('Asia/Shanghai');
        $sql = 'select lastupdate from pricecache where id='.$id;
        $callback = function($query_result){
            return $query_result[0]->lastupdate;;
        };
        $last_time = $this->db->db_query($sql,$callback);
        $now_time = strtotime('now');
        if($now_time == FALSE)
            die($this->log->log('strtotime() faild'));
        $time = $now_time-$last_time;
        if($time >= self::$UPDATE_TIME)
            return TRUE;
        else
            return FALSE;
    }
}
?>